function [resArr, resStruct] = parseXmlByTagName(filename, ElementTagName)
% PARSEXMLBYTAGNAME searches a XML file for elements with given name and
% returns an array
% 
%  resArr = [valueOfFirstFoundElement, valueOfSecondFoundElement, ...]
% 
% with the values of all found elements as well as a struct
% 
% resStruct.nodeName = 'char'
% resStruct.parentNodes = {'NodeNameOfParent', 'NodeNameOfParentParent', ...}
% 
% for every found element.

try
    tree = xmlread(filename);
catch
    error('Failed to read XML file %s.',filename);
end

% Recurse over XML tree and find the given element.
try
    [resArr, resStruct] = parseTree(tree, ElementTagName);
catch
    error('Unable to parse XML file %s or element %s not found.',filename, ElementTagName);
end


% ----- Subfunction PARSETREE -----
function [resArr, resStruct] = parseTree(tree, findStr)
% Find XML element by name
if tree.hasChildNodes
    theNode = tree.getElementsByTagName(findStr);

    for count = 1:theNode.getLength
        currNode = theNode.item(count-1);
        resArr(count) = str2double(currNode.getTextContent);
        resStruct(count).nodeName = char(currNode.getNodeName);
        
        % Get all parentNode for current XML element
        parentNode = currNode.getParentNode;
        parentNodeIdx = 1;
        while ~isempty(parentNode)
            resStruct(count).parentNodes{parentNodeIdx} = ...
                                              char(parentNode.getNodeName);
            parentNode = parentNode.getParentNode;
            parentNodeIdx = parentNodeIdx + 1;
        end%while
    end
end